#include "QtSQLite.h"

QtSQLite::QtSQLite()
{

}

void QtSQLite::test()
{
    qDebug() << "所有支持的数据库驱动:" << QSqlDatabase::drivers();

    //添加数据库驱动
    QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");

    //SQLite数据库
    QString databaseName = ":memory:";// 始终在内存中，程序退出数据丢失
//    databaseName = "sqlite.sqlite";//保存到磁盘上，数据可以重复使用
    database.setDatabaseName(databaseName);//设置数据库名

    //判断连接数据库是否成功
    if(!database.open())
    {
        qDebug() << "连接数据库失败：" << database.lastError().text();
        return ;
    }
    qDebug() << "创建数据库[" << databaseName << "]成功";

    //数据库查询
    QSqlQuery query;

    //创建表格
    query.exec("create table person (id int primary key, firstname varchar(20), lastname varchar(20))");
    qDebug() << "表格创建成功！";
    //批量预处理语句
    // ? 占位符（ODBC）
    query.prepare("insert into person(id, firstname, lastname) values(?, ?, ?)");
    //参数
    QVariantList ID, firstname, lastname;
    ID << 101 << 102 << 103;
    firstname << "chen" << "fan" << "zhai";
    lastname << "changhang" << "chen" << "wenhao";
    //占位符绑定参数
    query.addBindValue(ID);
    query.addBindValue(firstname);
    query.addBindValue(lastname);

    //批量执行
    query.execBatch();
    qDebug() << "批量预处理插入数据成功";

    //查询表格
    QString selectSql = "select id, firstname, lastname from person";
    query.exec(selectSql);
    qDebug() << "查询表格：" << selectSql ;
    while (query.next()) {
        qDebug() << query.value("ID").toInt()
                 << query.value("firstname").toString()
                 << query.value("lastname").toString();
    }

  \

}
